/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.phoenix.repository.query.jql;

import java.util.ArrayList;

import javax.jcr.query.InvalidQueryException;
import javax.jcr.query.qom.DynamicOperand;
import javax.jcr.query.qom.Ordering;
import javax.jcr.query.qom.QueryObjectModelConstants;

import net.phoenix.repository.query.jql.antlr.JQLTokenTypes;
import antlr.collections.AST;

/**
 * Jigsaw server
 * 
 * @author <a href="shamphone@gmail.com">Li XiongFeng</a>
 * @date 2012-4-22
 * @version 1.0.0
 */
public class OrderByAST extends JQLBaseAST {
	private Ordering[] orders;

	/**
	 * 
	 */
	private static final long serialVersionUID = -4450570864011655102L;

	public Ordering[] getOrderings() {
		if (this.orders == null) {
			ArrayList<Ordering> orders = new ArrayList<Ordering>();
			AST child = this.getFirstChild();
			while (child != null) {
				AST next = child.getNextSibling();
				if ((next != null) && (next.getType() == JQLTokenTypes.ASCENDING || next.getType() == JQLTokenTypes.DESCENDING)) {
					orders.add(new OrderingAST((DynamicOperand) child, (LiteralAST) next));
					child = next.getNextSibling();

				} else {
					orders.add(new OrderingAST((DynamicOperand) child));
					child = next;
				}
			}
			this.orders = orders.toArray(new Ordering[orders.size()]);
		}
		return this.orders;
	}

	
	
	@Override
	public String toJQL() {
		StringBuffer buffer = new StringBuffer("");
		AST child = this.getFirstChild();
		while (child != null) {
			if(buffer.length()>0)
				buffer.append(",");
			AST next = child.getNextSibling();
			if ((next != null) && (next.getType() == JQLTokenTypes.ASCENDING || next.getType() == JQLTokenTypes.DESCENDING)) {
				buffer.append(((JQLBaseAST)child).toJQL());
				buffer.append(" ");
				buffer.append(next.getText());
				child = next.getNextSibling();
			} else {
				buffer.append(((JQLBaseAST)child).toJQL());
				buffer.append(" ASC");
				child = next;
			}
		}
		buffer.insert(0, "ORDER BY ");
		return buffer.toString();
	}


	/* (non-Javadoc)
	 * @see net.phoenix.repository.query.parser.JQLBaseAST#generateSQL(net.phoenix.repository.query.parser.JQLQuery)
	 */
	@Override
	public void generateSQL(JQL2SQL collector) throws InvalidQueryException{
		StringBuffer buffer = new StringBuffer("");
		AST child = this.getFirstChild();
		while (child != null) {
			if(buffer.length()>0)
				buffer.append(",");
			AST next = child.getNextSibling();
			if ((next != null) && (next.getType() == JQLTokenTypes.ASCENDING || next.getType() == JQLTokenTypes.DESCENDING)) {
				((JQLBaseAST)child).generateSQL(collector);
				buffer.append(collector.pop());
				buffer.append(" ");
				buffer.append(next.getText());
				child = next.getNextSibling();
			} else {
				((JQLBaseAST)child).generateSQL(collector);
				buffer.append(collector.pop());
				buffer.append(" ASC");
				child = next;
			}
		}
		buffer.insert(0, "ORDER BY ");
		collector.push(buffer.toString());
	}



	class OrderingAST implements Ordering {
		private DynamicOperand oper;
		private LiteralAST order;

		public OrderingAST(DynamicOperand oper, LiteralAST order) {
			this.oper = oper;
			this.order = order;
		}

		public OrderingAST(DynamicOperand oper) {
			this.oper = oper;
			this.order = null;
		}

		@Override
		public DynamicOperand getOperand() {
			return this.oper;
		}

		public String toJQL() {
			StringBuffer buffer = new StringBuffer();
			buffer.append(((JQLBaseAST)oper).toJQL());
			buffer.append(" ");
			buffer.append(this.getOrder());
			return buffer.toString();
		}
		@Override
		public String getOrder() {
			if (this.order != null){
				if(this.order.getText().equalsIgnoreCase("asc"))
					return QueryObjectModelConstants.JCR_ORDER_ASCENDING;
				else 
					return QueryObjectModelConstants.JCR_ORDER_DESCENDING;
			}
			return QueryObjectModelConstants.JCR_ORDER_ASCENDING;
		}

	}
}
